
package com.zuul.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xcc.common.constant.SystemConstant;
import com.xcc.common.result.ResultBody;
import com.xcc.common.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;


/**
 * @author frosty
 * @description 设置过滤
 * @date 2019-11-13 13:11:15
 */


@Component
public class MyZuulFilter extends ZuulFilter {
    @Autowired(required = false)
   private RedisUtil redisUtil;



    private Logger logger= LoggerFactory.getLogger(MyZuulFilter.class);

/**
     * filterType：返回一个字符串代表过滤器的类型，
     * 在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
     * pre：路由之前
     * routing：路由之时
     * post： 路由之后
     * error：发送错误调用
     * @return
     */


    @Override
    public String filterType() {
        return "pre";
    }


/**
     * 过滤的顺序
     * @return
     */

    @Override
    public int filterOrder() {

        return 0;
    }


/**
     * 这里可以写逻辑判断，是否要过滤，本文true,永远过滤。
     * @return
     */

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        String result=null;
        ObjectMapper om=null;

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
          logger.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        String requestURI = request.getRequestURI();
        if(requestURI.contains("/login")){
            return null;
        }

        Object accessToken = request.getParameter("token");
      if(accessToken==null){
      accessToken=request.getHeader("token");
      }

        if(accessToken==null||StringUtils.isBlank(accessToken.toString())) {
             logger.warn("token is empty");
            ctx.setSendZuulResponse(false);  //这里去判断后面执行  true  执行  默认  false  不执行
            ctx.setResponseStatusCode(401);
            try {
                om=new ObjectMapper();
                result = om.writeValueAsString(ResultBody.error("token is empty"));
                ctx.getResponse().getWriter().write(result);

            }catch (Exception e){}

            return null;
        }
       //判断redis 中是否含有改token
       boolean hasKey = redisUtil.hasKey(accessToken.toString());
          if(!hasKey){
            ctx.setSendZuulResponse(false); //这里去判断后面执行  true  执行  默认  false  不执行
            om=new ObjectMapper();
            try {
                 result = om.writeValueAsString(ResultBody.error("token is error"));
                ctx.getResponse().getWriter().write(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //设置token时间
        redisUtil.expire(accessToken.toString(), SystemConstant.TOKEN_ACCENT_TIME);
          return null;
    }
}

